package com.jcli._自己的想法;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FirewallBlockerGUI extends JFrame {

    private JTextField programPathField;
    private JButton blockButton;

    public FirewallBlockerGUI() {
        setTitle("Firewall Blocker");
        setSize(400, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        initComponents();
    }

    private void initComponents() {
        JPanel panel = new JPanel();
        programPathField = new JTextField(20);
        blockButton = new JButton("Block Program");

        blockButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String programPath = programPathField.getText();
                blockProgram(programPath);
            }
        });

        panel.add(new JLabel("Program Path: "));
        panel.add(programPathField);
        panel.add(blockButton);

        add(panel);
    }

    private void blockProgram(String programPath) {
        try {
            // 构造命令
            String command = "netsh advfirewall firewall add rule name=\"BlockProgram\" dir=out action=block program=\"" + programPath + "\"";

            // 执行命令
            Process process = Runtime.getRuntime().exec(command);
            int exitCode = process.waitFor();

            // 检查命令是否执行成功
            if (exitCode == 0) {
                JOptionPane.showMessageDialog(this, "Blocked " + programPath + " successfully.");
            } else {
                JOptionPane.showMessageDialog(this, "Failed to block " + programPath + ".", "Error", JOptionPane.ERROR_MESSAGE);
            }

            // 打印命令执行的输出结果
            printCommandOutput(process);

        } catch (IOException | InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    private void printCommandOutput(Process process) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }

        JOptionPane.showMessageDialog(this, "Command Output:\n" + output.toString(), "Command Output", JOptionPane.INFORMATION_MESSAGE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FirewallBlockerGUI().setVisible(true);
            }
        });
    }
}
